package com.sdcqjy.property.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import com.sdcqjy.mylibrary.Logger;
import com.sdcqjy.mylibrary.OtherUtils;
import com.sdcqjy.property.R;
import com.sdcqjy.property.base.SimpleBaseActivity;
import com.sdcqjy.property.mode.ListMsgMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * webView展示页
 */
public class HtmlActivity extends SimpleBaseActivity {
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.textTitle)
    TextView textTitle;
    @BindView(R.id.textR)
    TextView textR;
    private ListMsgMode mode;

    public static void open(Context context, ListMsgMode mode) {
        Intent intent = new Intent(context, HtmlActivity.class);
        intent.putExtra("mode", mode);
        context.startActivity(intent);
    }

    @SuppressLint("JavascriptInterface")
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);
        Intent intent = getIntent();
        mode = intent.getParcelableExtra("mode");

        WebSettings settings = webView.getSettings();

        //缩放开关，设置此属性，仅支持双击缩放，不支持触摸缩放
        settings.setSupportZoom(true);
        //设置是否可缩放，会出现缩放工具（若为true则上面的设值也默认为true）
        settings.setBuiltInZoomControls(true);
        //隐藏缩放工具
        settings.setDisplayZoomControls(false);

        webView.setBackgroundColor(0xffFFffFF);

        settings.setJavaScriptEnabled(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setDomStorageEnabled(true);
        settings.setAllowFileAccess(true); //设置可以访问文件
        settings.setLoadsImagesAutomatically(true); //支持自动加载图片
        settings.setDefaultTextEncodingName("utf-8");//设置编码格式
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webView.setWebViewClient(new WebViewClient() {
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.out(url);
                if (url.equals("about:blank") || url.startsWith("mailto:")) {
                } else if (url.startsWith("tel:")) {//电话
                    OtherUtils.callTelOfUri(getActivity(), url);
                } else {
                    webView.loadUrl(url);
                }
                return true;
            }
        });
        webView.setWebChromeClient(new MyWebChromeClient());
        webView.setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength) -> {
            Uri uri = Uri.parse(url1);
            Intent intent1 = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent1);
            onBackPressed();
        });
        if (mode != null) {
            webView.loadUrl(mode.htmlPath);
            textTitle.setText(mode.title);
        }
    }

    protected void asynRun() {
        if (mode == null) {
            finish();
            return;
        }
        if (TextUtils.isEmpty(mode.documentPath) || TextUtils.isEmpty(mode.documentRealName)) {
            textR.setVisibility(View.GONE);
        } else textR.setVisibility(View.VISIBLE);
    }

    @OnClick({R.id.imgBack})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.imgBack:
                if (webView.canGoBack()) {
                    webView.goBack();// 返回前一个页面
                } else onBackPressed();
                break;
        }
    }

    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView.canGoBack()) {
                webView.goBack();// 返回前一个页面
            } else onBackPressed();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    @OnClick(R.id.textR)
    public void onViewClicked() {
        WordActivity.open(getActivity(), mode.documentPath);
    }

    /**
     * 继承WebChromeClient类
     * 对js弹出框时间进行处理
     */
    final class MyWebChromeClient extends WebChromeClient {

        /**
         * 处理alert弹出框
         */
        @Override
        public boolean onJsAlert(WebView view, String url,
                                 String message, JsResult result) {
            new AlertDialog.Builder(HtmlActivity.this).
                    setTitle("Alert").setMessage(message).setPositiveButton("OK",
                    (arg0, arg1) -> {
                        //TODO
                    }).create().show();
            result.confirm();
            return true;
        }

        /**
         * 处理confirm弹出框
         */
        @Override
        public boolean onJsConfirm(WebView view, String url, String message,
                                   JsResult result) {
            result.confirm();
            return super.onJsConfirm(view, url, message, result);
        }

        /**
         * 处理prompt弹出框
         */
        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            result.confirm();
            return super.onJsPrompt(view, url, message, message, result);
        }
    }
}
